package com.sgb.member.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.SparseArray;
import android.util.SparseIntArray;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.sgb.member.PickCateType;
import com.sgb.member.R;
import com.sgb.member.databinding.ActivityClientQualificationBinding;
import com.sgb.member.di.DaggerMemberComponent;
import com.sgb.member.di.MemberModule;
import com.sgb.member.entity.ClientQualificationBean;
import com.sgb.member.ui.adapter.ClientQualificationAdapter;
import com.sgb.member.view_model.ClientQualificationModel;
import com.swgk.core.base.AppActivity;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.MToast;
import com.swgk.core.view.areapopup.AddressEntity;
import com.swgk.core.view.areapopup.GoodsSourceLocationEntity;
import com.swgk.core.view.areapopup.ThreeLevelAreaWindow;
import com.swgk.core.view.selection.CommonPopEntity;
import com.swgk.core.view.selection.CopyUtils;
import com.swgk.core.view.selection.MemberStatusView;
import com.swgk.core.view.selection.XChooseDialog;
import com.swgk.core.view.selection.XChooseEntity;
import com.swgk.core.xrecyclerview.LoadingMoreFooter;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * Created by：冯齐 on 2021/1/26 16:41
 * Description：会员资质
 */
public class ClientQualificationActivity extends AppActivity implements MemberStatusView.OnChooseListener, XChooseDialog.DialogCallBackImpl {

    @Inject
    ClientQualificationModel viewModel;
    private ActivityClientQualificationBinding mBinding;

    private String mNo1; // 经营类型
    private String mNo3; // 资质类型
    private String mNo31;// 资质等级
    private String mNo4; // 省
    private String mNo5; // 市
    private String mNo6; // 备案单位省份
    private String mNo7; // 备案单位
    private CommonPopEntity mAll;

    // 经营地址Popup
    private ThreeLevelAreaWindow mAddressPop;
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> scrData;
    // 备案单位 根据省份走
    private List<CommonPopEntity> mFindUnitList;

    private ClientQualificationAdapter mAdapter;

    public static void start(Context context) {
        Intent intent = new Intent(context, ClientQualificationActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerMemberComponent.builder()
                .appComponent(appComponent)
                .memberModule(new MemberModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void initView() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_client_qualification);
        initSearchView();
        initPopup();
        initChooseDialog();
        initRecycler();

        loadSearchData(false);

    }

    private void loadSearchData(boolean isLoadMore) {
        viewModel.getQualifications(isLoadMore, mSearchText, mNo1, mNo3, mNo31, mNo4, mNo5, mNo6);
    }

    private void loadOtherData() {
        // 获取经营类型
        if (isListEmpty(PickCateType.TYPE_1)) {
            viewModel.getServiceTypeList(false);
        }
        // 资质等级
        if (isListEmpty(PickCateType.TYPE_3)) {
            viewModel.getQualifyTypeTreeList(false);
        }
        // 地区
        if (scrData == null) {
            viewModel.getAddressModel(false);
        }
        // 备案单位
        if (mFindUnitList == null) {
            viewModel.getFindDepartment();
        }
    }

    /**
     * --------------------------------- 搜索相关 -----------------------------------------------
     */
    private String mSearchText = ""; // 搜索内容

    private void initSearchView() {
        mBinding.activityBar.ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mBinding.activityBar.etView.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        mBinding.activityBar.etView.setHint("请输入公司名称或资质名称");
        mBinding.activityBar.etView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (TextUtils.isEmpty(mBinding.activityBar.etView.getText().toString())) {
                        MToast.showToast(getActivity(), "请输入公司名称或资质名称");
                        return true;
                    }
                    if (mSearchText.equals(mBinding.activityBar.etView.getText().toString())) {
                        MToast.showToast(getActivity(), "请输入不同的搜索内容");
                        return true;
                    }
                    mSearchText = mBinding.activityBar.etView.getText().toString().trim();
                    loadSearchData(false);
                }
                return false;
            }
        });
        mBinding.activityBar.etView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s) || s.length() == 0) {
                    mBinding.activityBar.tvSearchDelete.setVisibility(View.INVISIBLE);
                } else {
                    mBinding.activityBar.tvSearchDelete.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mBinding.activityBar.tvSearchDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSearchText = "";
                mBinding.activityBar.etView.setText("");
                loadSearchData(false);
            }
        });
        mBinding.activityBar.tvSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(mSearchText)) {
                    if (TextUtils.isEmpty(mBinding.activityBar.etView.getText().toString())) {
                        MToast.showToast(getActivity(), "请输入企业名称、资质标题");
                        return;
                    }
                }
                if (mSearchText.equals(mBinding.activityBar.etView.getText().toString())) {
                    MToast.showToast(getActivity(), "请输入不同的搜索内容");
                    return;
                }
                mSearchText = mBinding.activityBar.etView.getText().toString().trim();
                loadSearchData(false);
            }
        });
        mBinding.activityBar.tvSearchDelete.setVisibility(View.INVISIBLE);
    }

    /**
     * --------------------------------- Popup相关 -------------------------------------------------
     */

    public void initPopup() {
        mAll = new CommonPopEntity();
        mAll.setNo("");
        mAll.setTypeName("全部");
        mBinding.popup1.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        mBinding.popup3.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        mBinding.popupAddress.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        mBinding.chooseLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < mData.size(); i++) {
                    XChooseEntity chooseEntity = mData.get(mData.keyAt(i));
                    int sort = chooseEntity.getSort();
                    if (sort == PickCateType.TYPE_1
                            || sort == PickCateType.TYPE_3
                            || sort == PickCateType.TYPE_4
                            || sort == PickCateType.TYPE_6) {
                        if (chooseEntity.getList() == null || chooseEntity.getList().size() == 0) {
                            loadOtherData();
                            return;
                        }
                    }
                }
                mData.get(PickCateType.TYPE_6).setHide(TextUtils.isEmpty(mNo4));
                mChooseDialog.initData(mData, mFilters);
                mChooseDialog.showDialog();
            }
        });
        mBinding.popupAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (scrData == null) {
                    viewModel.getAddressModel(true);
                } else {
                    showAddressPopup();
                }
            }
        });
        initAddressPopup();
    }

    private void initAddressPopup() {
        mAddressPop = new ThreeLevelAreaWindow(getActivity());
        mAddressPop.setBgView(mBinding.grayLayout);
        mAddressPop.setMemberHeight();
        mAddressPop.setCitySingle();
        mAddressPop.setProvinceSingle();
        mAddressPop.setShowSimpleName(true);
        mAddressPop.setOnlyShowProAndCity(true);
        mAddressPop.setAllSingleSelect(true);
        mAddressPop.setThreeListIsGone(true);
        mAddressPop.setOnResultClick(new ThreeLevelAreaWindow.OnResultClickProxy() {
            @Override
            protected void result(GoodsSourceLocationEntity entity) {
                mNo4 = "";
                mNo5 = "";
                mNo6 = "";
                mFilters.put(PickCateType.TYPE_4, mAddressPop.getProvincePosition());
                addMainEntity(PickCateType.TYPE_5, new ArrayList<>());
                addMainEntity(PickCateType.TYPE_6, new ArrayList<>());
                mBinding.popupAddress.updateChooseTextStatus(0, mBinding.popupAddress.getKeyName());
                if (!TextUtils.isEmpty(entity.getProvinceNo())) {
                    mNo4 = entity.getProvinceNo();
                    mBinding.popupAddress.updateChooseTextStatus(1, entity.getProvinceName());
                    mFilters.put(PickCateType.TYPE_4, mAddressPop.getProvincePosition());
                    updateCityData(new CommonPopEntity(entity.getProvinceNo(), entity.getProvinceName()), mFilters.get(PickCateType.TYPE_4), false);
                    if (!TextUtils.isEmpty(entity.getCityNo())) {
                        mNo5 = entity.getCityNo();
                        mBinding.popupAddress.updateChooseTextStatus(1, entity.getCityName());
                        mFilters.put(PickCateType.TYPE_5, mAddressPop.getmCityPosition());
                    }
                }
                //刷新数据
                loadSearchData(false);
            }
        });
        mAddressPop.setOnDismissListener(() -> {
            mBinding.popLine.setVisibility(View.GONE);
            if (!TextUtils.isEmpty(mNo4) || !TextUtils.isEmpty(mNo5)) {
                mBinding.popupAddress.updateChooseTextStatus(1, null);
            } else {
                mBinding.popupAddress.updateChooseTextStatus(0, mBinding.popupAddress.getKeyName());
            }
        });
    }

    private void showAddressPopup() {
        mBinding.popLine.setVisibility(View.VISIBLE);
        if (!TextUtils.isEmpty(mNo4) || !TextUtils.isEmpty(mNo5)) {
            mBinding.popupAddress.updateChooseTextStatus(-2, null);
        } else {
            mBinding.popupAddress.updateChooseTextStatus(-1, mBinding.popupAddress.getKeyName());
        }
        mAddressPop.showPopwindow0(mBinding.popLine);
    }

    // 经营类型回调
    public void setServiceTypeList(boolean isShowPopup, List<CommonPopEntity> data) {
        if (data == null || data.size() == 0) return;
        data.add(0, mAll);
        addMainEntity(PickCateType.TYPE_1, data);
        mBinding.popup1.setData(data);
        if (isShowPopup) {
            mBinding.popup1.showPop();
        }
    }

    // 资质类型回调
    public void setQualifyTypes(boolean isShowPopup, List<CommonPopEntity> data) {
        if (data == null || data.size() == 0) return;
        data.add(0, mAll);
        mBinding.popup3.setData(data);
        addMainEntity(PickCateType.TYPE_3, data);
        addMainEntity(PickCateType.TYPE_31, new ArrayList<>());
        if (isShowPopup) {
            mBinding.popup3.showPop();
        }
    }

    public void setAddressData(boolean isShowPopup, List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data, List<CommonPopEntity> entities) {
        if (data != null && data.size() > 0) {
            scrData = data;
            entities.add(0, mAll);
            addMainEntity(PickCateType.TYPE_4, entities);
            if (TextUtils.isEmpty(mNo4)) {
                mAddressPop.setData(data, true);
            } else {
                mAddressPop.setDataAndPosition(data, mNo4, mNo5, "", true, true);
            }
            if (isShowPopup) {
                showAddressPopup();
            }
        }
    }

    public void setAddressCityData(boolean isShowLeftDialog, List<CommonPopEntity> data) {
        if (data != null && data.size() > 0) {
            data.add(0, mAll);
            if (isShowLeftDialog) {
                mChooseDialog.addEntity(PickCateType.TYPE_5, data);
            } else {
                addMainEntity(PickCateType.TYPE_5, data);
            }
        }
    }

    // 备案单位回调
    public void getFindDepartment(List<CommonPopEntity> data) {
        if (data == null || data.size() == 0) return;
        addMainEntity(PickCateType.TYPE_6, data);
        mFindUnitList = data;
    }

    // 备案单位联动回调
    public void setFindUnitByProvinceNo(boolean isShowLeftDialog, List<CommonPopEntity> children) {
        boolean isEmptyList = children == null || children.size() == 0;
        if (!isEmptyList) {
            children.add(0, mAll);
        }
        if (isShowLeftDialog) {
            mChooseDialog.addEntity(PickCateType.TYPE_6, children, isEmptyList);
        } else {
            addMainEntity(PickCateType.TYPE_6, children, isEmptyList);
        }
    }

    public void addMainEntity(int index, List<CommonPopEntity> list) {
        addMainEntity(index, list, false);
    }

    public void addMainEntity(int index, List<CommonPopEntity> list, boolean isHide) {
        if (mData.get(index) != null) {
            if (list == null || list.size() == 0) {
                mData.get(index).setList(new ArrayList<>());
            } else {
                mData.get(index).setList(list);
            }
        } else {
            mData.put(index, new XChooseEntity(index, mNameArray.get(index), list));
        }
        mFilters.put(index, 0);
        mChooseDialog.addEntity(index, list);
    }

    // Popup 按照分类加载数据
    @Override
    public void onLoadChooseData(String mKeyName) {
        if (mNameArray.get(PickCateType.TYPE_3).equals(mKeyName)) { // 资质类型
            viewModel.getQualifyTypeTreeList(true);
        } else if (mNameArray.get(PickCateType.TYPE_1).equals(mKeyName)) { // 经营类型
            viewModel.getServiceTypeList(true);
        }
    }

    // Popup Item点击事件
    @Override
    public void onChooseResult(String mKeyName, CommonPopEntity entity, Object... objects) {
        int position = (int) objects[0];
        String no = position == 0 ? "" : entity.getNo();
        String id = position == 0 ? "" : entity.getId();
        String code = position == 0 ? "" : entity.getCode();
        if (mNameArray.get(PickCateType.TYPE_3).equals(mKeyName)) { // 资质类型
            if (!TextUtils.equals(no, mNo3)) {
                mNo3 = no;
                mNo31 = "";
                mFilters.put(PickCateType.TYPE_3, position);
                // 联动资质类型数据更新
                updateQualificationLever(entity, position, false);
                loadSearchData(false);
            }
        } else if (mNameArray.get(PickCateType.TYPE_1).equals(mKeyName)) { // 经营类型
            if (!TextUtils.equals(code, mNo1)) {
                mNo1 = code;
                mFilters.put(PickCateType.TYPE_1, position);
                loadSearchData(false);
            }
        }
    }

    public void addMainEntity(int index, String name, List<CommonPopEntity> list) {
        if (!TextUtils.isEmpty(name)) {
            mNameArray.put(index, name);
        }
        if (mData.get(index) != null) {
            mData.get(index).setTypeName(mNameArray.get(index));
            if (list == null || list.size() == 0) {
                mData.get(index).setList(new ArrayList<>());
            } else {
                mData.get(index).setList(list);
            }
        } else {
            mData.put(index, new XChooseEntity(index, mNameArray.get(index), list));
        }
        mFilters.put(index, 0);
    }

    /**
     * ------------------------------------ 侧滑刷选 ----------------------------------------
     */

    private XChooseDialog mChooseDialog;
    // 数据集
    private SparseArray<XChooseEntity> mData = new SparseArray<>();
    // 本地缓存筛选结果
    private SparseIntArray mFilters = new SparseIntArray();
    private SparseArray<String> mNameArray = new SparseArray<>();

    private void initChooseDialog() {
        mNameArray.put(PickCateType.TYPE_1, "经营类型");
        mNameArray.put(PickCateType.TYPE_3, "资质类型");
        mNameArray.put(PickCateType.TYPE_31, "资质等级");
        mNameArray.put(PickCateType.TYPE_4, "省份");
        mNameArray.put(PickCateType.TYPE_5, "市区");
        mNameArray.put(PickCateType.TYPE_6, "备案单位");
        mChooseDialog = new XChooseDialog(this, mNameArray);
        mChooseDialog.setCallBack(this);
        for (int i = 0; i < mNameArray.size(); i++) {
            addMainEntity(mNameArray.keyAt(i), new ArrayList<>());
        }
    }

    @Override
    public void loadChildData(XChooseEntity entity, int pos) {
        if (entity.getSort() == PickCateType.TYPE_3) {
            updateQualificationLever(entity.getList().get(pos), pos, true);
            mChooseDialog.showDialog();
        } else if (entity.getSort() == PickCateType.TYPE_4) {
            updateCityData(entity.getList().get(pos), pos, true);
            mChooseDialog.showDialog();
        }
    }

    /**
     * 更新资质等级数据集合
     */
    private void updateQualificationLever(CommonPopEntity entity, int pos, boolean isShowLeftDialog) {
        List<CommonPopEntity> tempList = new ArrayList<>();
        if (isShowLeftDialog) {
            mChooseDialog.addEntity(PickCateType.TYPE_31, tempList);
        } else {
            addMainEntity(PickCateType.TYPE_31, tempList);
        }
        if (pos > 0) {
            List<CommonPopEntity> children = entity.getChildren();
            if (children != null && children.size() > 0) {
                tempList.add(0, mAll);
                for (CommonPopEntity child : children) {
                    CommonPopEntity obj = new CommonPopEntity(child.getNo(), child.getTypeName());
                    tempList.add(obj);
                }
                if (isShowLeftDialog) {
                    mChooseDialog.addEntity(PickCateType.TYPE_31, tempList);
                } else {
                    addMainEntity(PickCateType.TYPE_31, tempList);
                }
            }
        }
    }

    private void updateCityData(CommonPopEntity entity, int pos, boolean isShowLeftDialog) {
        if (isShowLeftDialog) {
            mChooseDialog.addEntity(PickCateType.TYPE_5, new ArrayList<>());
            mChooseDialog.addEntity(PickCateType.TYPE_6, new ArrayList<>());
        } else {
            addMainEntity(PickCateType.TYPE_5, new ArrayList<>());
            addMainEntity(PickCateType.TYPE_6, new ArrayList<>());
        }
        if (pos > 0) {
            viewModel.getDepartmentChoose(mFindUnitList, entity.getNo(), isShowLeftDialog);
            viewModel.getAddressCityData(scrData, entity.getNo(), PickCateType.TYPE_5, isShowLeftDialog);
        }
    }

    private boolean isListEmpty(int catType) {
        return mData.get(catType) != null &&
                (mData.get(catType).getList() == null || mData.get(catType).getList().size() == 0);
    }

    @Override
    public void result(SparseArray<XChooseEntity> data, SparseIntArray map) {
        mData = CopyUtils.deepPopEntityCopy(data);
        mFilters = map.clone();
        for (int i = 0; i < mData.size(); i++) {
            XChooseEntity entity = mData.get(mData.keyAt(i));
            int key = entity.getSort();
            int value = mFilters.get(key);
            switch (key) {
                case PickCateType.TYPE_1:
                    mNo1 = entity.getItemCode(value);
                    mBinding.popup1.refreshChoose(mNo1, entity.getItemName(value), value);
                    break;
                case PickCateType.TYPE_3:
                    mNo3 = entity.getItemNo(value);
                    mBinding.popup3.refreshChoose(mNo3, entity.getItemName(value), value);
                    break;
                case PickCateType.TYPE_31:
                    mNo31 = entity.getItemNo(value);
                    break;
                case PickCateType.TYPE_4:
                    mNo4 = entity.getItemNo(value);
                    mBinding.popupAddress.refreshChoose(mNo4, entity.getItemName(value), value);
                    mAddressPop.setDefPosition(value, 0);
                    break;
                case PickCateType.TYPE_5:
                    mNo5 = entity.getItemNo(value);
                    mAddressPop.setDefPosition(mFilters.get(PickCateType.TYPE_4), value);
                    if (value > 0) {
                        mBinding.popupAddress.refreshChoose(mNo5, entity.getItemName(value), value);
                    }
                    break;
                case PickCateType.TYPE_6:
                    if(!TextUtils.isEmpty(mNo4)){
                        mNo6 = entity.getItemNo(value);
                    } else {
                        mNo6 = "";
                    }
                    break;
                default:
                    break;
            }
        }
        loadSearchData(false);
    }

    @Override
    public void reset() {
        mFilters.clear();
        result(mData, mFilters);
        mChooseDialog.initData(mData, mFilters);
        mChooseDialog.showDialog();
    }

    @Override
    public void onCancel() {
        mChooseDialog.initData(mData, mFilters);
    }

    /**
     * --------------------------------- recyclerView相关 -------------------------------
     */

    private void initRecycler() {
        TextView textView = mBinding.memberEmptyView.findViewById(R.id.no_data_count);
        textView.setVisibility(View.VISIBLE);
        mBinding.recyclerView.setPullRefreshEnabled(true);
        mBinding.recyclerView.setLoadingMoreEnabled(true);
        LoadingMoreFooter footer = (LoadingMoreFooter) mBinding.recyclerView.getFootView();
        footer.setNoMoreHint("已经到底啦~");
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new ClientQualificationAdapter(this, null);
        mBinding.recyclerView.setAdapter(mAdapter);
        mBinding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                loadSearchData(false);
            }

            @Override
            public void onLoadMore() {
                loadSearchData(true);
            }
        });
        mAdapter.setOnItemClick(new AdapterOnItemClick<ClientQualificationBean>() {
            @Override
            public void onItemClick(ClientQualificationBean clientQualificationBean, int position) {
                viewModel.getUrlSetting("qualifications", clientQualificationBean.getId());
            }
        });
    }

    public void showEmpty() {
        mBinding.recyclerView.refreshComplete();
        mBinding.recyclerView.loadMoreComplete();
        mAdapter.clearDatas();
        mBinding.memberEmptyView.setVisibility(View.VISIBLE);
    }

    public void refreshRecycler(List<ClientQualificationBean> list, boolean isLoadMore, boolean isLastPage) {
        mBinding.recyclerView.setVisibility(View.VISIBLE);
        if (isLoadMore) {
            mBinding.recyclerView.loadMoreComplete();
            if (list != null && list.size() > 0) {
                mAdapter.addDatas(list);
            }
            mBinding.recyclerView.setNoMore(isLastPage);
        } else {
            mBinding.recyclerView.refreshComplete();
            if (list != null && list.size() > 0) {
                mBinding.memberEmptyView.setVisibility(View.GONE);
                mAdapter.setDatas(list);
            } else {
                mAdapter.clearDatas();
                mBinding.memberEmptyView.setVisibility(View.VISIBLE);
            }
        }
    }
}
